package com.example.sxt_practise.IO;

import java.io.*;

/**
 * @author gaofeng
 * @date 2022年05月08日 19:15
 */
public class ByteArrayToFile {
    public static void main(String[] args) {
        File picture = new File("receive.jpeg") ;
        byte[] byteArray = fileToByteArray("receive.jpeg");
        byteArrayToFile(byteArray, new File("receive_byte_array_copy.jpeg")) ;
    }

    /**
     * 将文件写出到字节数组中
     * @author gaofeng
     * @date  2022/5/8 19:30
     * @param filePath
     * @return byte[]
     */
    public static byte[] fileToByteArray(String filePath) {
        // 1.创建源和目的地
        File file = new File(filePath) ;
        byte[] dest = new byte[1024] ;
        // 2.选择流
        InputStream inputStream = null ;
        ByteArrayOutputStream byteArrayOutputStream = null ;
        try {
            // 3.操作,写入到字节数组中
            inputStream = new FileInputStream(file) ;
            byteArrayOutputStream = new ByteArrayOutputStream() ;
            byte[] flush = new byte[1024] ;
            int len = -1 ;
            while ((len = inputStream.read(flush)) != -1) {
                byteArrayOutputStream.write(flush, 0, len);
            }
            byteArrayOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null ;
    }

    public static void byteArrayToFile(byte[] source, File file) {
        // 2.选择流
        InputStream inputStream = null ;
        OutputStream outputStream = null ;
        try {
            inputStream = new ByteArrayInputStream(source) ;
            outputStream = new FileOutputStream(file) ;
            // 3. 操作,将字节数组输出到文件
            byte[] flush = new byte[1024 * 2] ;
            int len = -1 ;
            while ((len = inputStream.read(flush)) != -1) {
                outputStream.write(source);
            }
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
